import axios from 'axios'
import qs from 'qs'
import { getToken } from '@/utils/auth'
import { useAuthStore } from '@/stores/auth'
const getUrl = () => {
  const url = new URL(window.location.href)
  const params = new URLSearchParams(url.search)

  // 要移除的参数列表
  const paramsToRemove = ['authorizationCode', 'accessToken', 'access_token']

  // 移除指定参数
  paramsToRemove.forEach((param) => params.delete(param))

  // 重新构建 URL
  const newUrl = `${url.origin}${url.pathname}${
    params.toString() ? '?' + params.toString() : ''
  }`
  return newUrl
}
class HttpRequest {
  constructor(baseUrl) {
    this.baseUrl = baseUrl
  }

  interceptors(instance) {
    instance.interceptors.request.use(
      (config) => {
        const token = getToken()
        if (token) {
          config.headers['Authorization'] = 'Bearer ' + token
        }
        // 在发送请求之前做些什么
        return config
      },
      (error) => {
        // 对请求错误做些什么
        return Promise.reject(error)
      },
    )

    instance.interceptors.response.use(
      (response) => {
        const authStore = useAuthStore()
        const code = response.data.code || 200 // 仅检查 response.data.code
        if (code === 10002) {
          authStore.loginOut().then((ssoUrl) => {
            location.href = ssoUrl + encodeURIComponent(getUrl())
          })
        }
        return response
      },
      (error) => {
        if (error.response && error.response.status === 401) {
          console.error('Unauthorized, redirecting to login...')
        }
        return Promise.reject(error)
      },
    )
  }

  post(url, params = {}, contentType = '', otherParams = {}) {
    const axiosInstance = axios.create()
    this.interceptors(axiosInstance)
    return axiosInstance.post(this.baseUrl + url, params, otherParams)
  }

  qsPost(url, params = {}, contentType = '') {
    const axiosInstance = axios.create()
    this.interceptors(axiosInstance)
    return axiosInstance.post(this.baseUrl + url, qs.stringify(params))
  }

  qsPut(url, params = {}, contentType = '') {
    const axiosInstance = axios.create()
    this.interceptors(axiosInstance)
    return axiosInstance.put(this.baseUrl + url, qs.stringify(params))
  }

  get(url, params = {}, contentType = '') {
    const axiosInstance = axios.create()
    this.interceptors(axiosInstance)
    return axiosInstance.get(this.baseUrl + url, { params })
  }

  deleteData(url, params = {}, contentType = '') {
    const axiosInstance = axios.create()
    this.interceptors(axiosInstance)
    return axiosInstance.delete(this.baseUrl + url, { data: params })
  }
}

export default HttpRequest
